"""
    PartnerGate application
    Handles events used for PartnerGate url management
    (ex" /partner_id/url?callback=func)
"""
from flask import Flask, g, Blueprint, request, make_response
from decorators import gate_response
from models import DataAccess

pgate = Blueprint('pgate', __name__)


@pgate.route("/<int:partner_id>/<md5:url>", methods=['GET'], strict_slashes=False)
@gate_response(expires="+7d", max_age=604800)
def access(partner_id, url):
    first_seen = 0
    first_seen = g.db.get_url(partner_id, url)
    if first_seen <= 0:
        first_seen = g.db.add_url(partner_id, url)	

    resp = str(first_seen)

    # move to decorator function
    callback = request.args.get("callback")
    if callback:
        resp = "%s(%s);\n" % (callback, resp)

    return resp

@pgate.before_request
def before_request():
    g.db = DataAccess()

@pgate.after_request
def after_request(response):
    g.db.close()
    return response